package com;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Properties;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.Log4jFactory;

public class JavaProgramBean {
	public String className;
	public String content;
	public String codeText;
	public String output = "output will appear here";
	public String selClassName;
	public volatile List listOfFiles;
	public volatile List listOfJarFiles;
	public String[] selectedJarList;
	public volatile List availableJarList;
	public String selJarToDel;
	public String userName;
	public String ajaxText;
	private boolean notJavaFile = false;
	private boolean disNavigation = false;
	public UserDetails userDetails;
	private String currentSessionFiles;
	private boolean isError = false;
	private String consoleColor = "color : black";

	private volatile List<ClassBean> recentFilesList;

	private static Log logger = Log4jFactory.getLog(JavaProgramBean.class);

	public void setUserDetails(UserDetails userDetails) {
		this.userDetails = userDetails;
	}

	public List<SelectItem> getListOfFiles() {
		listOfFiles = new ArrayList();
		// System.out.println("with in the get List");

		File sourceDir = new File(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+"/createdJavaFiles");

		if (sourceDir.isDirectory()) {
			// commenting to load only java files
			// File fileName[] = sourceDir.listFiles(new
			// FileNameFilterExt("java"));
			File fileName[] = sourceDir.listFiles(new FileNameFilterExt(
					IDEConstants.DOT_JAVA + ":" + IDEConstants.DOT_TXT + ":"
							+ IDEConstants.DOT_PROPERTIES + ":"
							+ IDEConstants.DOT_HTML + ":"
							+ IDEConstants.DOT_XML));

			for (int i = 0; i < fileName.length; i++) {
				// System.out.println("JavaProgrammingBean : getListOfFiles "+fileName[i].getName());
				if (!fileName[i].getName()
						.equals(IDEConstants.OUTPUT_FILE_NAME)
						&& !fileName[i].getName().equalsIgnoreCase(
								IDEConstants.COMPILE_OUTPUT_FILE_NAME)
						&& !fileName[i].getName()
								.equals(IDEConstants.BUILD_XML)
						&& !fileName[i].getName().equals(
								IDEConstants.SAVE_OUTPUT_FILE)
						&& !fileName[i].getName().equals(
								IDEConstants.RECENT_FILE)) {
					// System.out.println("reserved files except....");
					ClassBean classBean = new ClassBean();
					// System.out.println(fileName[i]);
					classBean.setClassName(fileName[i].getName());
					classBean.setClassAbsPath(fileName[i].getAbsolutePath());
					listOfFiles.add(classBean);
				}
			}
		}
		Collections.sort(listOfFiles, COMPARATORCLASS);
		if (listOfFiles.size() > IDEConstants.NUMBER_OF_FILES) {
			disNavigation = true;
		}
		// constructing the recent files list, this will be useful to show most
		// recent files when use logs out
		try {
			// user logs at first time then only open the last viewed file
			if (userDetails.isFirstTime()) {
				recentFilesList = new ArrayList<ClassBean>();
				Properties props = new Properties();
				props.load(new FileInputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+"/createdJavaFiles/currentSessionFiles.properties"));
				System.out.println("props.getProperty(currentFiles):"
						+ props.getProperty("currentFiles"));
				StringBuffer buffer = null;
				buffer = new StringBuffer(props.getProperty("currentFiles"));
				if (buffer != null && buffer.toString() != null
						&& !buffer.toString().trim().equals("")) {
					String recentFiles[] = buffer.toString().split(":");
					for (int i = 0; i < recentFiles.length; i++) {
						System.out
								.println("javaprogrammingbean:getListOfFiles:in loop: "
										+ recentFiles[i]);
						ClassBean classBean = new ClassBean();
						classBean.setRecentFile(recentFiles[i].substring(0,
								recentFiles[i].length()));
						recentFilesList.add(classBean);
					}
				}
				System.out
						.println("JavaProgramming getListOfFiles:recentFilesList.size():"
								+ recentFilesList.size());
				if (recentFilesList.size() > 0) {
					ClassBean classBean = recentFilesList.get(0);
					System.out
							.println("JavaProgramming getListOfFiles:classBean.getClassName():"
									+ classBean.getRecentFile());
					selClassName = classBean.getRecentFile();
					System.out
							.println("JavaProgramming getListOfFiles:selClassName:"
									+ selClassName);
					openAction();
				}
				userDetails.setFirstTime(false);
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return listOfFiles;
	}

	public List getAvailableJarList() {
		availableJarList = new ArrayList();
		// System.out.println("with in the availableJarList get List");
		File sourceDir = new File(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+"/createdJavaFiles/selectedJars");
		if (sourceDir.isDirectory()) {
			// System.out.println("some one killed JSP");
			File fileName[] = sourceDir.listFiles(new FileNameFilterExt("jar"));
			// System.out.println("some one killed JSP:"+fileName.length);
			for (int i = 0; i < fileName.length; i++) {
				ClassBean classBean = new ClassBean();
				// System.out.println("available jar name Jar file Name :"+fileName[i]);
				classBean.setJarName(fileName[i].getName());
				classBean.setJarAbsPath(fileName[i].getAbsolutePath());
				availableJarList.add(classBean);
			}

		}
		return availableJarList;
	}

	public String openAction() {
		// System.out.println("with in the openAction");
		if (selClassName != null) {
			System.out.println("selClassName:" + selClassName);
			logger.debug("This is first time logger:" + selClassName);
			File openSelFile = new File(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/createdJavaFiles/" + selClassName);
			codeText = readSelectedFile(openSelFile.getAbsolutePath());
			className = selClassName;
			// checkForNonJavaFile();
			// Open current session files
			System.out.println("JavaProgrammingBean : openAction :className:"
					+ className);
			recentFilesList = new ArrayList<ClassBean>();
			currentSessionFiles = null;
			try {
				Properties props = new Properties();
				props.load(new FileInputStream(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"));
				System.out.println("props.getProperty(currentFiles):"
						+ props.getProperty("currentFiles"));
				StringBuffer buffer = null;
				buffer = new StringBuffer(props.getProperty("currentFiles"));
				String tempString = null;
				System.out.println("javaprogramming openAction buffer:"
						+ buffer.toString());
				if (buffer != null && buffer.toString() != null
						&& !buffer.toString().trim().equals("")) {
					if (buffer.indexOf(className) < 0) {
						tempString = buffer.append(className + ":").toString();
						// tempString =
						// tempString.substring(0,tempString.length()-1);
						props.put("currentFiles", tempString);
						props.store(
								new FileOutputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
								"Saving CurrentFiles");
						System.out.println("after props.getProperty(currentFiles):"	+ props.getProperty("currentFiles"));
					} else {
						tempString = props.getProperty("currentFiles");
					}
				} else {
					if (buffer.indexOf(className) < 0) {
						tempString = buffer.append(className + ":").toString();
						// tempString =
						// tempString.substring(0,tempString.length()-1);
						props.put("currentFiles", tempString);
						props.store(
								new FileOutputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
								"Saving CurrentFiles");
						System.out
								.println("after props.getProperty(currentFiles):"
										+ props.getProperty("currentFiles"));
					} else {
						tempString = props.getProperty("currentFiles");
					}
				}
				if (tempString != null && tempString.indexOf(":") > 0) {
					currentSessionFiles = tempString.substring(0,
							tempString.length() - 1);
				} else {
					currentSessionFiles = tempString;
				}
				System.out.println("Final currentSessionFiles::"
						+ currentSessionFiles);

				if (currentSessionFiles != null
						&& currentSessionFiles.indexOf(":") > 0) {
					String recentFiles[] = currentSessionFiles.split(":");
					for (int i = 0; i < recentFiles.length; i++) {
						System.out
								.println("javaprogrammingbean:openaction:in loop: "
										+ recentFiles[i]);
						ClassBean classBean = new ClassBean();
						classBean.setRecentFile(recentFiles[i].substring(0,
								recentFiles[i].length()));
						recentFilesList.add(classBean);
					}
				} else {
					System.out
							.println("javaprogrammingbean:openaction:in else:"
									+ tempString);
					ClassBean classBean = new ClassBean();
					classBean.setRecentFile(currentSessionFiles);
					recentFilesList.add(classBean);
				}
				tempString = null;
				System.out.println("recentFilesList size:"
						+ recentFilesList.size());
			} catch (FileNotFoundException FNF) {
				FNF.printStackTrace();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		consoleColor = "color : black";
		return "success";
	}

	public String modAction() {
		// System.out.println("with in the modAction");
		// System.out.println("className in mod :"+className);
		// System.out.println("selClassName:"+selClassName);
		File openSelFile = new File(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/createdJavaFiles/" + selClassName);
		codeText = readSelectedFile(openSelFile.getAbsolutePath());
		className = selClassName;
		return "success";
	}

	public String deleteAction() {
		File deleteSelFile = new File(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/createdJavaFiles/" + selClassName);
		if (deleteSelFile.exists()) {
			deleteSelFile.delete();

		}
		try {
			System.out.println(":::deleteAction:ClassName::::" + selClassName);
			recentFilesList = new ArrayList<ClassBean>();
			Properties props = new Properties();
			props.load(new FileInputStream(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"));
			System.out.println("props.getProperty(currentFiles):"
					+ props.getProperty("currentFiles"));
			StringBuilder buffer = null;
			currentSessionFiles = null;
			buffer = new StringBuilder(props.getProperty("currentFiles"));
			System.out
					.println("javaprogramming:deleteAction:buffer before index check :>>"
							+ buffer.toString());
			System.out
					.println("javaprogramming:deleteAction:buffer before index className :>>"
							+ selClassName.length());
			System.out
					.println("javaprogramming:deleteAction:buffer before buffer.indexOf(selClassName) :>>"
							+ buffer.indexOf(selClassName));
			currentSessionFiles = buffer.toString();
			String nextFile = null;
			if (currentSessionFiles != null
					&& currentSessionFiles.indexOf(":") > 0) {
				String recentFiles[] = currentSessionFiles.split(":");
				for (int i = 0; i < recentFiles.length; i++) {
					if (recentFiles[i].equals(selClassName)
							|| recentFiles[i].equals(selClassName + ":")) {
						if (i == 0) {
							System.out
									.println("javaprogramming:deleteAction:deleting:if:FirstFile");
							nextFile = recentFiles[(recentFiles.length) - 1];
							System.out
									.println("javaprogramming:deleteAction:deletingnextFile>>"
											+ nextFile);
							break;
						} else {
							nextFile = recentFiles[i - 1];
							System.out
									.println("javaprogramming:deleteAction:deletingnextFile in else>>"
											+ nextFile);
							break;
						}
					}
				}
			}
			System.out
					.println("javaprogramming:deleteAction:after getting the desired file:>>"
							+ nextFile);
			currentSessionFiles = null;
			if (buffer.indexOf(selClassName) >= 0) {
				System.out
						.println("javaprogramming:deleteAction:starting index >>"
								+ buffer.indexOf(selClassName));
				System.out.println("javaprogramming:deleteAction:ClassName >>"
						+ selClassName.length());
				String tempString = buffer.toString().replace(
						selClassName + ":", "");
				if (tempString != null && !tempString.trim().equals("")) {
					currentSessionFiles = tempString.substring(0,
							tempString.length());
				}

				// buffer.delete(buffer.indexOf(className), clasLength);
				System.out
						.println("javaprogramming:deleteAction:before placing tempString >>"
								+ tempString);
				if (currentSessionFiles != null) {
					props.put("currentFiles", currentSessionFiles);
					props.store(
							new FileOutputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
							"Saving CurrentFiles");
					System.out
							.println("deleteAction: after props.getProperty(currentFiles):"
									+ props.getProperty("currentFiles"));
					String recentFiles[] = currentSessionFiles.split(":");
					for (int i = 0; i < recentFiles.length; i++) {
						System.out
								.println("javaprogrammingbean:deleteAction:in loop: "
										+ recentFiles[i]);
						ClassBean classBean = new ClassBean();
						classBean.setRecentFile(recentFiles[i].substring(0,
								recentFiles[i].length()));
						recentFilesList.add(classBean);
					}
				} else {
					props.put("currentFiles", "");
					props.store(
							new FileOutputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
							"Saving CurrentFiles");
					System.out
							.println("deleteAction: else props.getProperty(currentFiles):"
									+ props.getProperty("currentFiles"));

				}
				tempString = null;
			}
			// adding nextfile to open
			if (currentSessionFiles != null && nextFile != null
					&& !nextFile.trim().equals("")) {
				selClassName = nextFile;
				openAction();
			} else {
				System.out
						.println("javaprogramming:deleteAction data has been cleared...");
				clear();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	public String deleteRecent() {
		try {
			System.out.println(":::deleteRecent:ClassName::::" + selClassName);
			recentFilesList = new ArrayList<ClassBean>();
			Properties props = new Properties();
			props.load(new FileInputStream(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"));
			System.out.println("props.getProperty(currentFiles):"
					+ props.getProperty("currentFiles"));
			StringBuilder buffer = null;
			currentSessionFiles = null;
			buffer = new StringBuilder(props.getProperty("currentFiles"));
			System.out
					.println("javaprogramming:deleteRecent:buffer before index check :>>"
							+ buffer.toString());
			System.out
					.println("javaprogramming:deleteRecent:buffer before index className :>>"
							+ selClassName.length());
			System.out
					.println("javaprogramming:deleteRecent:buffer before buffer.indexOf(selClassName) :>>"
							+ buffer.indexOf(selClassName));
			currentSessionFiles = buffer.toString();
			String nextFile = null;
			if (currentSessionFiles != null
					&& currentSessionFiles.indexOf(":") > 0) {
				String recentFiles[] = currentSessionFiles.split(":");
				for (int i = 0; i < recentFiles.length; i++) {
					if (recentFiles[i].equals(selClassName)
							|| recentFiles[i].equals(selClassName + ":")) {
						if (i == 0) {
							System.out
									.println("javaprogramming:deleteRecent:deleting:if:FirstFile");
							nextFile = recentFiles[(recentFiles.length) - 1];
							System.out
									.println("javaprogramming:deleteRecent:deletingnextFile>>"
											+ nextFile);
							break;
						} else {
							nextFile = recentFiles[i - 1];
							System.out
									.println("javaprogramming:deleteRecent:deletingnextFile in else>>"
											+ nextFile);
							break;
						}
					}
				}
			}
			System.out
					.println("javaprogramming:deleteRecent:after getting the desired file:>>"
							+ nextFile);
			currentSessionFiles = null;
			if (buffer.indexOf(selClassName) >= 0) {
				System.out
						.println("javaprogramming:deleteRecent:starting index >>"
								+ buffer.indexOf(selClassName));
				System.out.println("javaprogramming:deleteRecent:ClassName >>"
						+ selClassName.length());
				String tempString = buffer.toString().replace(
						selClassName + ":", "");
				if (tempString != null && !tempString.trim().equals("")) {
					currentSessionFiles = tempString.substring(0,
							tempString.length());
				}

				// buffer.delete(buffer.indexOf(className), clasLength);
				System.out
						.println("javaprogramming:deleteRecent:before placing tempString >>"
								+ tempString);
				if (currentSessionFiles != null) {
					props.put("currentFiles", currentSessionFiles);
					props.store(
							new FileOutputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
							"Saving CurrentFiles");
					System.out
							.println("eleteRecent: after props.getProperty(currentFiles):"
									+ props.getProperty("currentFiles"));
					String recentFiles[] = currentSessionFiles.split(":");
					for (int i = 0; i < recentFiles.length; i++) {
						System.out
								.println("javaprogrammingbean:deleteRecent:in loop: "
										+ recentFiles[i]);
						ClassBean classBean = new ClassBean();
						classBean.setRecentFile(recentFiles[i].substring(0,
								recentFiles[i].length()));
						recentFilesList.add(classBean);
					}
				} else {
					props.put("currentFiles", "");
					props.store(
							new FileOutputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
							"Saving CurrentFiles");
					System.out
							.println("deleteRecent: else props.getProperty(currentFiles):"
									+ props.getProperty("currentFiles"));

				}
				tempString = null;
			}
			// adding nextfile to open
			if (currentSessionFiles != null && nextFile != null
					&& !nextFile.trim().equals("")) {
				selClassName = nextFile;
				openAction();
			} else {
				System.out
						.println("javaprogramming:deleteRecent data has been cleared...");
				clear();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	public String deleteJar() {
		File deleteSelJarFile = new File(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/createdJavaFiles/selectedJars/"
				+ selJarToDel);
		// System.out.println("with in delete Jar "+deleteSelJarFile);
		if (deleteSelJarFile.exists()) {
			deleteSelJarFile.delete();

		}
		return "success";
	}

	public List<SelectItem> getListOfJarFiles() {
		listOfJarFiles = new ArrayList();
		// System.out.println("with in the get List");
		File sourceDir = new File(NewGmailUser.getSelectedContextPath()+File.separator+"SourceFolder/createdJavaFiles/jars");
		if (sourceDir.isDirectory()) {
			File fileName[] = sourceDir.listFiles(new FileNameFilterExt("jar"));

			for (int i = 0; i < fileName.length; i++) {
				// System.out.println(fileName[i]);
				listOfJarFiles.add(new SelectItem(
						fileName[i].getAbsolutePath(), fileName[i].getName()));
			}

		}
		Collections.sort(listOfJarFiles, COMPARATORJAR);
		return listOfJarFiles;
	}

	public String saveProgram() {

		if (className.indexOf(IDEConstants.DOT_JAVA) > 0) {
			String classFullPath = createJavaFile(className, codeText);
			System.out.println("runProgram : " + className);
			System.out.println("codeText : " + codeText);
			if (className == null || className.trim().equals("")) {
				System.out.println("class name null or empty");
				FacesMessage message = new FacesMessage(
						"Class Name is required");
				FacesContext.getCurrentInstance().addMessage(
						"Class Name is required", message);
				return "success";
			}
			if (codeText == null || codeText.trim().equals("")) {
				System.out.println("content name null or empty");
				FacesMessage message = new FacesMessage(
						"File Content is required");
				FacesContext.getCurrentInstance().addMessage(
						"File Content is required", message);
				return "success";
			}
			if (codeText == null || (!codeText.trim().equals("") && 
					(codeText.trim().startsWith(IDEConstants.PACKAGE_NAME) || 
							codeText.trim().startsWith(IDEConstants.PACKAGE_NAME_COM)))) {
				System.out.println("package name does not required, because all the files in default package");
				FacesMessage message = new FacesMessage(
						"package name does not required, because all the files in default package");
				FacesContext.getCurrentInstance().addMessage(
						"package name does not required, because all the files in default package", message);
				return "success";
			}
			String mainClassName = null;
			if (className != null && !className.trim().equals("")
					&& className.indexOf(IDEConstants.DOT_JAVA) < 0) {
				mainClassName = className.concat(IDEConstants.DOT_JAVA);
				className = mainClassName;
			} else {
				mainClassName = className;
			}

			for (int i = 0; i < selectedJarList.length; i++) {
				System.out.println("runprogram :" + selectedJarList[i]);
				String onlyFileName = selectedJarList[i].substring(
						selectedJarList[i].lastIndexOf(File.separator) + 1,
						selectedJarList[i].length());
				System.out.println("onlyFileName only only::" + onlyFileName);
				copySelectedJarFile(selectedJarList[i], onlyFileName);
			}
		} else if (className.indexOf(IDEConstants.DOT_PROPERTIES) > 0) {
			System.out
					.println("javaprogrammingbean:saveprogram:with in the properties file ");
			String propFilePath = createJavaFile(className, codeText);
		} else if (className.indexOf(IDEConstants.DOT_TXT) > 0) {
			System.out
					.println("javaprogrammingbean:saveprogram:with in the txt file ");
			String txtFilePath = createJavaFile(className, codeText);
		} else if (className.indexOf(IDEConstants.DOT_HTML) > 0) {
			System.out
					.println("javaprogrammingbean:saveprogram:with in the html file ");
			String txtHtmlPath = createJavaFile(className, codeText);
		} else if (className.indexOf(IDEConstants.DOT_XML) > 0) {
			System.out
					.println("javaprogrammingbean:saveprogram:with in the xml file ");
			String txtXmlPath = createJavaFile(className, codeText);
		}
		output = "file saved successfully.........";

		// saving recent files

		System.out.println("JavaProgrammingBean : saveProgram :className:"
				+ className);
		recentFilesList = new ArrayList<ClassBean>();
		currentSessionFiles = null;
		try {
			Properties props = new Properties();
			props.load(new FileInputStream(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"));
			System.out.println("props.getProperty(currentFiles):"
					+ props.getProperty("currentFiles"));
			StringBuffer buffer = null;
			buffer = new StringBuffer(props.getProperty("currentFiles"));
			String tempString = null;
			System.out.println("javaprogramming saveProgram buffer:"
					+ buffer.toString());
			if (buffer != null && buffer.toString() != null
					&& !buffer.toString().trim().equals("")) {
				if (buffer.indexOf(className) < 0) {
					tempString = buffer.append(className + ":").toString();
					// tempString =
					// tempString.substring(0,tempString.length()-1);
					props.put("currentFiles", tempString);
					props.store(
							new FileOutputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
							"Saving CurrentFiles");
					System.out.println("after props.getProperty(currentFiles):"
							+ props.getProperty("currentFiles"));
				} else {
					tempString = props.getProperty("currentFiles");
				}
			} else {
				if (buffer.indexOf(className) < 0) {
					tempString = buffer.append(className + ":").toString();
					// tempString =
					// tempString.substring(0,tempString.length()-1);
					props.put("currentFiles", tempString);
					props.store(
							new FileOutputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
							"Saving CurrentFiles");
					System.out.println("after props.getProperty(currentFiles):"
							+ props.getProperty("currentFiles"));
				} else {
					tempString = props.getProperty("currentFiles");
				}
			}
			if (tempString != null && tempString.indexOf(":") > 0) {
				currentSessionFiles = tempString.substring(0,
						tempString.length() - 1);
			} else {
				currentSessionFiles = tempString;
			}
			System.out.println("Final currentSessionFiles::"
					+ currentSessionFiles);

			if (currentSessionFiles != null
					&& currentSessionFiles.indexOf(":") > 0) {
				String recentFiles[] = currentSessionFiles.split(":");
				for (int i = 0; i < recentFiles.length; i++) {
					System.out
							.println("javaprogrammingbean:saveProgram:in loop: "
									+ recentFiles[i]);
					ClassBean classBean = new ClassBean();
					classBean.setRecentFile(recentFiles[i].substring(0,
							recentFiles[i].length()));
					recentFilesList.add(classBean);
				}
			} else {
				System.out.println("javaprogrammingbean:saveProgram:in else:"
						+ tempString);
				ClassBean classBean = new ClassBean();
				classBean.setRecentFile(currentSessionFiles);
				recentFilesList.add(classBean);
			}
			tempString = null;
			System.out
					.println("recentFilesList size:" + recentFilesList.size());
		} catch (FileNotFoundException FNF) {
			FNF.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		consoleColor = "color : black";
		return "success";
	}

	public String runProgram() {

		// return the javaide if class name and class content is empty or null
		System.out.println("runProgram : " + className);
		System.out.println("codeText : " + codeText);
		if (className == null || className.trim().equals("")) {
			System.out.println("class name null or empty");
			FacesMessage message = new FacesMessage("Class Name is required");
			FacesContext.getCurrentInstance().addMessage(
					"Class Name is required", message);
			return "success";
		}
		if (codeText == null || codeText.trim().equals("")) {
			System.out.println("content name null or empty");
			FacesMessage message = new FacesMessage("Code Content is required");
			FacesContext.getCurrentInstance().addMessage(
					"Code Content is required", message);
			return "success";
		}
		if (codeText == null || (!codeText.trim().equals("") && 
				(codeText.trim().startsWith(IDEConstants.PACKAGE_NAME) || 
						codeText.trim().startsWith(IDEConstants.PACKAGE_NAME_COM)))) {
			System.out.println("package name does not required, because all the files in default package");
			FacesMessage message = new FacesMessage(
					"package name does not required, because all the files in default package");
			FacesContext.getCurrentInstance().addMessage(
					"package name does not required, because all the files in default package", message);
			return "success";
		}
		Java2Ant java2Ant = new Java2Ant();
		String mainClassName = null;
		if (className != null && !className.trim().equals("")
				&& className.indexOf(IDEConstants.DOT_JAVA) < 0) {
			mainClassName = className.concat(IDEConstants.DOT_JAVA);
			className = mainClassName;
		} else {
			mainClassName = className;
		}

		for (int i = 0; i < selectedJarList.length; i++) {
			System.out.println("runprogram :" + selectedJarList[i]);
			String onlyFileName = selectedJarList[i].substring(
					selectedJarList[i].lastIndexOf(File.separator) + 1,
					selectedJarList[i].length());
			System.out.println("onlyFileName only only::" + onlyFileName);
			copySelectedJarFile(selectedJarList[i], onlyFileName);
		}

		boolean mainClassFlag = false;
		String classFullPath = createJavaFile(className, codeText);

		if (codeText != null && codeText.length() > 0) {
			if (codeText.contains(IDEConstants.MAIN_METHOD)
					|| codeText.contains(IDEConstants.MAIN_METHOD1)
					|| codeText.contains(IDEConstants.MAIN_METHOD2)
					|| codeText.contains(IDEConstants.MAIN_METHOD3)) {
				mainClassFlag = true;
			}
		}
		System.out.println("main class name ::: " + mainClassName);
		String buildStatus = java2Ant.executeBuild(classFullPath, StringUtils
				.subStringOnChar(mainClassName, IDEConstants.DOT_JAVA),
				mainClassFlag, this.userDetails.getUsername());

		System.out.println("buildStatus in Java Programming bean "
				+ buildStatus);
		if (buildStatus != null && "succeeded".equals(buildStatus)) {
			if (mainClassFlag) {
				output = readOutputFile();
				consoleColor = "color : black";

			} else {
				// System.out.println("file doest not has main method");
				output = readSaveOutputFile();
				consoleColor = "color : black";

			}
		} else {
			output = readCompileFile();
			isError = true;
			consoleColor = "color : red";
		}

		System.out.println("JavaProgrammingBean : runProgram :className:"
				+ className);
		recentFilesList = new ArrayList<ClassBean>();
		currentSessionFiles = null;
		try {
			Properties props = new Properties();
			props.load(new FileInputStream(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"));
			System.out.println("props.getProperty(currentFiles):"
					+ props.getProperty("currentFiles"));
			StringBuffer buffer = null;
			buffer = new StringBuffer(props.getProperty("currentFiles"));
			String tempString = null;
			System.out.println("javaprogramming runProgram buffer:"
					+ buffer.toString());
			if (buffer != null && buffer.toString() != null
					&& !buffer.toString().trim().equals("")) {
				if (buffer.indexOf(className) < 0) {
					tempString = buffer.append(className + ":").toString();
					// tempString =
					// tempString.substring(0,tempString.length()-1);
					props.put("currentFiles", tempString);
					props.store(
							new FileOutputStream(
									NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
							"Saving CurrentFiles");
					System.out.println("after props.getProperty(currentFiles):"
							+ props.getProperty("currentFiles"));
				} else {
					tempString = props.getProperty("currentFiles");
				}
			} else {
				if (buffer.indexOf(className) < 0) {
					tempString = buffer.append(className + ":").toString();
					// tempString =
					// tempString.substring(0,tempString.length()-1);
					props.put("currentFiles", tempString);
					props.store(
							new FileOutputStream(
									NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/currentSessionFiles.properties"),
							"Saving CurrentFiles");
					System.out.println("after props.getProperty(currentFiles):"
							+ props.getProperty("currentFiles"));
				} else {
					tempString = props.getProperty("currentFiles");
				}
			}
			if (tempString != null && tempString.indexOf(":") > 0) {
				currentSessionFiles = tempString.substring(0,
						tempString.length() - 1);
			} else {
				currentSessionFiles = tempString;
			}
			System.out.println("Final currentSessionFiles::"
					+ currentSessionFiles);

			if (currentSessionFiles != null
					&& currentSessionFiles.indexOf(":") > 0) {
				String recentFiles[] = currentSessionFiles.split(":");
				for (int i = 0; i < recentFiles.length; i++) {
					System.out
							.println("javaprogrammingbean:runProgram:in loop: "
									+ recentFiles[i]);
					ClassBean classBean = new ClassBean();
					classBean.setRecentFile(recentFiles[i].substring(0,
							recentFiles[i].length()));
					recentFilesList.add(classBean);
				}
			} else {
				System.out.println("javaprogrammingbean:runProgram:in else:"
						+ tempString);
				ClassBean classBean = new ClassBean();
				classBean.setRecentFile(currentSessionFiles);
				recentFilesList.add(classBean);
			}
			tempString = null;
			System.out
					.println("recentFilesList size:" + recentFilesList.size());
		} catch (FileNotFoundException FNF) {
			FNF.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return "success";
	}

	public String clear() {
		System.out.println("data has been cleared...");
		className = "";
		codeText = "";
		output = "";
		notJavaFile = true;
		return "success";
	}

	public String selectedClass() {
		// System.out.println("selected class Name "+selClassName);
		return "success";
	}

	private void copySelectedJarFile(String fileName, String onlyFileName) {
		File dirName = new File(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/" + IDEConstants.SEL_JAR_FOLDER);
		if (!dirName.isDirectory()) {
			dirName.mkdir();
		}
		try {
			File f1 = new File(fileName);
			File f2 = new File(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/" + IDEConstants.SEL_JAR_FOLDER
					+ "/" + onlyFileName);
			InputStream in = new FileInputStream(f1);

			// For Append the file.
			// OutputStream out = new FileOutputStream(f2,true);

			// For Overwrite the file.
			OutputStream out = new FileOutputStream(f2);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
			// System.out.println("File copied.");
		} catch (FileNotFoundException ex) {
			// System.out.println(ex.getMessage() +
			// " in the specified directory.");
			System.exit(0);
		} catch (IOException e) {
			// System.out.println(e.getMessage());
		}

	}

	private String createJavaFile(String fileName, String content) {
		File dirName = new File(IDEConstants.FOLDER_ON_SERVER);
		if (!dirName.isDirectory()) {
			dirName.mkdir();
		}
		File file = new File(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/" + fileName);
		try {

			Writer writer = new BufferedWriter(new FileWriter(file));
			writer.write(content);
			writer.close();
			System.out.println("ABS PATH ::::::::" + file.getAbsolutePath());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return file.getAbsolutePath();

	}

	private String readSelectedFile(String fileName) {
		byte bytes[] = new byte[0];
		String value = null;
		try {
			// //System.out.println("buffer read out");
			/*
			 * File file = new File(
			 * "E:/eDMSoftwares/eclipse-jee-indigo-win32/eclipse/createdJavaFiles/output.txt"
			 * ); if(file.exists()){ file.delete(); }
			 */
			FileInputStream fis = new FileInputStream(fileName);
			File file = new File(fileName);
			bytes = new byte[(int) file.length()];
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length
					&& (numRead = fis
							.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}
			value = new String(bytes);
			fis.close();
			// //System.out.println(value);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	private String readOutputFile() {
		byte bytes[] = new byte[0];
		String value = null;
		try {
			// //System.out.println("buffer read out");
			/*
			 * File file = new File(
			 * "E:/eDMSoftwares/eclipse-jee-indigo-win32/eclipse/createdJavaFiles/output.txt"
			 * ); if(file.exists()){ file.delete(); }
			 */
			FileInputStream fis = new FileInputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/createdJavaFiles/output.txt");
			File file = new File(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/createdJavaFiles/output.txt");
			bytes = new byte[(int) file.length()];
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length
					&& (numRead = fis
							.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}
			value = new String(bytes);
			fis.close();
			// //System.out.println(value);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	private String readCompileFile() {
		byte bytes[] = new byte[0];
		String value = null;
		try {
			// //System.out.println("buffer read out");
			/*
			 * File file = new File(
			 * "E:/eDMSoftwares/eclipse-jee-indigo-win32/eclipse/createdJavaFiles/output.txt"
			 * ); if(file.exists()){ file.delete(); }
			 */
			FileInputStream fis = new FileInputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()+ "/createdJavaFiles/compileOutPut.txt");
			File file = new File(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/createdJavaFiles/compileOutPut.txt");
			bytes = new byte[(int) file.length()];
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length
					&& (numRead = fis
							.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}
			value = new String(bytes);
			fis.close();
			// //System.out.println(value);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}

	private String readSaveOutputFile() {
		byte bytes[] = new byte[0];
		String value = null;
		try {
			// //System.out.println("buffer read out");
			/*
			 * File file = new File(
			 * "E:/eDMSoftwares/eclipse-jee-indigo-win32/eclipse/createdJavaFiles/output.txt"
			 * ); if(file.exists()){ file.delete(); }
			 */
			FileInputStream fis = new FileInputStream(NewGmailUser.getSelectedContextPath()+IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser()
					+ "/createdJavaFiles/saveoutput.txt");
			File file = new File(NewGmailUser.getSelectedContextPath() +IDEConstants.USERS_FOLDER+File.separator+getCurrrentUser() + "/createdJavaFiles/saveoutput.txt");
			bytes = new byte[(int) file.length()];
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length
					&& (numRead = fis
							.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}
			value = new String(bytes);
			fis.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return value;
	}
	String getCurrrentUser() {
		return this.userDetails.getUsername();
	}
	public String logout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
		session.invalidate();
		return "thanksPage";
	}

	private static Comparator<ClassBean> COMPARATORCLASS = new Comparator<ClassBean>() {
		public int compare(ClassBean o1, ClassBean o2) {
			return o1.getClassName().compareTo(o2.getClassName());
		}
	};
	private static Comparator<SelectItem> COMPARATORJAR = new Comparator<SelectItem>() {
		public int compare(SelectItem o1, SelectItem o2) {
			return o1.getValue().toString().compareTo(o2.getValue().toString());
		}
	};

	public String changePassword() {
		return "changePassword";
	}

	public String getAjaxTextValue() {
		System.out.println("with in the getAjaxTextValue");
		System.out.println("ajaxText::::" + ajaxText);
		this.output = ajaxText;
		return "success";
	}

	public String checkForNonJavaFile() {
		System.out.println("JavaprogrammingBean:checkForNonJavaFile:entry");
		if (className != null
				&& className.indexOf(IDEConstants.DOT_PROPERTIES) > 0) {
			notJavaFile = false;
			System.out
					.println("JavaprogrammingBean:checkForNonJavaFile:DOT_PROPERTIES:"
							+ notJavaFile);
		} else if (className != null
				&& className.indexOf(IDEConstants.DOT_XML) > 0) {
			notJavaFile = false;
			System.out
					.println("JavaprogrammingBean:checkForNonJavaFile:DOT_XML:"
							+ notJavaFile);
		} else if (className != null
				&& className.indexOf(IDEConstants.DOT_TXT) > 0) {
			notJavaFile = false;
			System.out
					.println("JavaprogrammingBean:checkForNonJavaFile:DOT_TXT:"
							+ notJavaFile);
		} else if (className != null
				&& className.indexOf(IDEConstants.DOT_HTML) > 0) {
			notJavaFile = false;
			System.out
					.println("JavaprogrammingBean:checkForNonJavaFile:DOT_HTML:"
							+ notJavaFile);
		} else if (className != null && className.indexOf(IDEConstants.DOT) > 0) {
			String ext = className
					.substring(className.indexOf(IDEConstants.DOT) + 1,
							className.length());
			if (ext != null
					&& ("ja".equals(ext) || "jav".equals(ext) || "java"
							.equals(ext))) {
				notJavaFile = true;
			}
			System.out
					.println("JavaprogrammingBean:checkForNonJavaFile:javafile:"
							+ notJavaFile);
		}
		System.out.println("JavaprogrammingBean:checkForNonJavaFile:exit");
		return null;

	}

	public boolean isDisNavigation() {
		return disNavigation;
	}

	public void setDisNavigation(boolean disNavigation) {
		this.disNavigation = disNavigation;
	}

	public String getPrevNextSearch(ActionEvent event) {
		return "success";
	}

	public List<ClassBean> getRecentFilesList() {
		return recentFilesList;
	}

	public void setRecentFilesList(List<ClassBean> recentFilesList) {
		this.recentFilesList = recentFilesList;
	}

	public void setListOfJarFiles(List listOfJarFiles) {
		this.listOfJarFiles = listOfJarFiles;
	}

	public void setListOfFiles(List<SelectItem> listOfFiles) {
		this.listOfFiles = listOfFiles;
	}

	public String getSelClassName() {
		return selClassName;
	}

	public void setSelClassName(String selClassName) {
		this.selClassName = selClassName;
	}

	public String getOutput() {
		return output;
	}

	public void setOutput(String output) {
		this.output = output;
	}

	public String getCodeText() {
		return codeText;
	}

	public void setCodeText(String codeText) {
		this.codeText = codeText;
	}

	public String getClassName() {
		return className;
	}

	public void setClassName(String className) {
		this.className = className;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String[] getSelectedJarList() {
		return selectedJarList;
	}

	public void setSelectedJarList(String[] selectedJarList) {
		this.selectedJarList = selectedJarList;
	}

	public void setAvailableJarList(List availableJarList) {
		this.availableJarList = availableJarList;
	}

	public String getSelJarToDel() {
		return selJarToDel;
	}

	public void setSelJarToDel(String selJarToDel) {
		this.selJarToDel = selJarToDel;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public boolean isNotJavaFile() {
		return notJavaFile;
	}

	public void setNotJavaFile(boolean notJavaFile) {
		this.notJavaFile = notJavaFile;
	}

	public String getAjaxText() {
		return ajaxText;
	}

	public void setAjaxText(String ajaxText) {
		this.ajaxText = ajaxText;
	}

	public String getCurrentSessionFiles() {
		return currentSessionFiles;
	}

	public void setCurrentSessionFiles(String currentSessionFiles) {
		this.currentSessionFiles = currentSessionFiles;
	}

	public boolean isError() {
		return isError;
	}

	public void setError(boolean isError) {
		this.isError = isError;
	}

	public String getConsoleColor() {
		return consoleColor;
	}

	public void setConsoleColor(String consoleColor) {
		this.consoleColor = consoleColor;
	}

}